﻿using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using CefSharp;
using pinduoduo.Page;
using pinduoduo.Util;
using Sunny.UI;
using Utils;

namespace pinduoduo
{
    public partial class Main : UIHeaderMainFrame
    {

        public MainPage mainPage { get; }
        public MainAccountPage TokenPage { get; }
        public OrderPage orderPage { get; }
        
        public RequestContext AccountContext { get; set; }
        public SettingPage settingPage { get; set; }

        public Main()
        {
            InitializeComponent();


            //设置关联
            Header.TabControl = MainTabControl;

            mainPage = new MainPage(this);
            TokenPage = new MainAccountPage(this);
            orderPage = new OrderPage();
            //增加页面到Main
            AddPage(mainPage, 1001);
            AddPage(TokenPage, 1002);
            AddPage(orderPage, 1003);
            AddPage(new AddressPage(this), 1004);
            AddPage(new CommentForm(), 1005);
            AddPage(new SettingPage(), 1006);
            //设置Header节点索引
            Header.SetNodePageIndex(Header.Nodes[0], 1001);
            Header.SetNodePageIndex(Header.Nodes[1], 1002);
            Header.SetNodePageIndex(Header.Nodes[2], 1003);
            Header.SetNodePageIndex(Header.Nodes[3], 1004);
            Header.SetNodePageIndex(Header.Nodes[4], 1005);
            Header.SetNodePageIndex(Header.Nodes[5], 1006);

            string styleStr = IniHelper.GetPrivateProfileString("STARTUP", "Style", IniHelper.IniPathFile, 500);
            int styleIndex = 0;
             int.TryParse(styleStr, out styleIndex);
            StyleManager.Style = (UIStyle)styleIndex;
           //Header.SetNodeSymbol(Header.Nodes[3], 61502);
           var styles = UIStyles.PopularStyles();
            foreach (UIStyle style in styles)
            {
                Header.CreateChildNode(Header.Nodes[6], style.DisplayText(), style.Value());
            }

            //显示默认界面
            Header.SelectedIndex = 0;

            Version newVersion = Assembly.GetExecutingAssembly().GetName().Version;
            this.Text = this.Text + "         到期时间：" + G_Api.Cur_VipUser.expireDate +"              软件版本："+ newVersion;

            MonitorExpirTask();
            MonitorExpirTask2();

        }

        public override void SelectPage(int pageIndex)
        {
            Header.SelectedIndex=pageIndex;
        }

        private double CurServerTime = SystemUtil.GetTimeStamp();


        private async void MonitorExpirTask()
        {
            string curTimeStr = await G_Api.GetServerTime();
            if (string.IsNullOrWhiteSpace(curTimeStr))
            {
                ShowErrorDialog("与服务器连接失败");
                return;
            }
            DateTime expireDate = (DateTime)G_Api.Cur_VipUser.expireDate;
            var expireTime = SystemUtil.GetTimeStamp(expireDate);
            CurServerTime = double.Parse(curTimeStr);
            await Task.Run(() =>
            {
                while (true)
                {
                    CurServerTime += 1000;
                    if (expireTime < CurServerTime)
                    {
                        ShowErrorDialog("您的软件到期，请充值！");
                        this.BeginInvoke(new Action(() =>
                        {
                            this.Close();
                        }));

                        System.Environment.Exit(0);
                        break;
                    }
                    Thread.Sleep(1000);
                }
            });
        }

        private async void MonitorExpirTask2()
        {
            await Task.Run(async () =>
            {
                while (true)
                {
                    var softwareExpire = await G_Api.SoftwareExpire();

                    if (!softwareExpire)
                    {
#if !DEBUG
                        this.BeginInvoke(new Action(() =>
                        {
                            this.Close();
                        }));
                        System.Environment.Exit(0);
                        break;
#endif
                    }
                    AutoUpdate.GetInstance().updater.BeginCheckUpdateInProcess();
                    Thread.Sleep(1000 * 60 * 10);
                }
            });
        }

        private void Main_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            if (ShowAskDialog("您确定退出登录吗"))
            {
                Cef.Shutdown();
                System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void Header_MenuItemClick(string itemText, int menuIndex, int pageIndex)
        {
            switch (menuIndex)
            {
                case 0:
                case 1:
                case 2:
                    //Aside.SelectPage(pageIndex);
                    break;

                case 6:
                    UIStyle style = (UIStyle)pageIndex;
                    StyleManager.Style = style;
                    IniHelper.WriteKeyToIni("STARTUP", "Style", pageIndex.ToString(), IniHelper.IniPathFile);
                    break;
            }
            if (itemText == "订单管理")
            {
                orderPage.UpdateData();
            }
            if (itemText == "主账号")
            {
                TokenPage.UpdateData();
            }
        }
    }
}
